﻿using System;
using System.ComponentModel;

using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Interactivity.InteractionRequest;
using System.Windows.Input;
using System.Windows;
using Microsoft.Practices.Prism.Regions;
using UserAccountModule.Views;
using ServiceAgent.CatalogueService;
using Microsoft.Practices.Prism.ViewModel;
using ServiceAgent;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Prism.Events;
using UserAccountModule.Commands;
using ServiceAgent.UserAccountService;
using Infrastructure;
using Infrastructure.Events;
using Infrastructure.Account;
using UserAccountModule.Services;
using System.ServiceModel;

namespace UserAccountModule.ViewModels
{
    public class LoginViewModel : NotificationObject
    {
        #region Fields
        private readonly IEventAggregator eventAggregator;
        private readonly IUnityContainer container;
        private readonly IRegionManager regionManager;

        string userName;
        string password;

        #endregion

        #region Constructor
        /// <summary>
        /// Default constructor.
        /// </summary>
        public LoginViewModel(IEventAggregator eventAggregator, IRegionManager regionManager, IUnityContainer container)
        {
            this.eventAggregator = eventAggregator;
            this.regionManager = regionManager;
            this.container = container;

            //this.container.RegisterType<Object, AddDanTocView>("AddDanTocView");
            this.LoginCommand = new DelegateCommand(this.OnRaiseLogin);
        }
        #endregion

        #region Command Properties
        public DelegateCommand LoginCommand { get; private set; }
        #endregion

        #region Administrative Properties
        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }

        public string Password
        {
            get { return password; }
            set { password = value; }
        }
        #endregion

        #region Private Methods
        private void OnRaiseLogin()
       { 
            try
            {
                using (var proxy = container.Resolve<UserAccountServiceAgent>())
                {
                    var result = proxy.GetUserByUserNamePassword(UserName.Trim(), Password.Trim());

                    LocalAccountService.StoreAccount(result);
                    eventAggregator.GetEvent<LoginCompletedEvent>().Publish(true);
                }
            }
            catch (FaultException e)
            {
                MessageBox.Show(e.Message);
            }
            catch (CommunicationException)
            {
                MessageBox.Show("Không thể kết nối tới máy chủ");
            }

            finally { }
        }
        #endregion
    }
}